<template>
  <div class="userInfo">
      <h1>个人信息</h1>
    <el-form :model="userForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item>
        <el-image
            v-if="userForm.photoUrl"
            style="width: 100px; height: 100px;border-radius:50%"
            :src="userForm.photoUrl"
            :preview-src-list="[userForm.photoUrl]">
        </el-image>
      </el-form-item>
      <el-upload
          class="upload-demo"
          action="fuck"
          :before-upload="beforeAvatarUpload"
          list-type="picture">
        <el-button size="small" type="primary">更换头像</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2mb</div>
      </el-upload>
        <el-form-item label="学校/校区" prop="region" class="item1">
          <p>{{schoolName}}/{{campusName}}</p>
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="userForm.studentId"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNo">
          <el-input v-model="userForm.phoneNo"></el-input>
        </el-form-item>
      <el-form-item label="个性签名" prop="personalSignature">
          <el-input v-model="userForm.personalSignature"></el-input>
        </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="userForm.userName"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="studentName">
        <p>{{userForm.studentName}}</p>
      </el-form-item>
      <el-form-item size="small" class="me-login-button">
        <el-button type="primary" @click.native.prevent="submitForm('ruleForm')">保存并修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {fileRequest, reqUserInfo} from "@/api";
import {mapState} from "vuex";
import {Message} from "element-ui";

export default {
  name: "UserInfoIndex",
  data() {
    return {
      schoolName:'',
      campusName:'',
      userForm: {
        photoUrl:undefined,
        id:undefined,
        userName: undefined,
        studentName: undefined,
        phoneNo: undefined,
        personalSignature: undefined,
        studentId: undefined,
      },
      rules: {
        userName: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {max: 10, message: '不能大于10个字符', trigger: 'blur'}
        ],
        studentName: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {max: 10, message: '不能大于10个字符', trigger: 'blur'}
        ],
        phoneNo: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
        ],
        personalSignature: [
          {required: true, message: '请输入个性签名', trigger: 'blur'},
        ],
        studentId: [
          {required: true, message: '请输入学号', trigger: 'blur'},
        ]
      },
    };
  },
  computed: {
    ...mapState({
      getuserInfo: state => state.user.userInfo,
    }),
  },
    methods: {
      beforeAvatarUpload(image) {
        console.log(image)
        const isJpgOrPng = image.type === "image/jpeg" || image.type === "image/png" || image.type === "image/webp";
        const isLt2M = image.size / 1024 / 1024 < 2;

        if (!isJpgOrPng) {
          this.$message.error("上传头像图片只能是 JPG/PNG/WEBP 格式!");
          return false;
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
          return false;
        }
        let uploadfile = new FormData();
        const loading = this.$loading({
          lock: true,
          text: '上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        uploadfile.append("image", image);
        fileRequest("/order/upload", uploadfile).then((response) => {
          if (response) {
            loading.close();
            this.userForm.photoUrl = response
            this.$message({message: '上传成功', type: 'success', showClose: true});
          }
        });
        return false;
      },
      submitForm(formName) {
        let that = this
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            that.userForm.id = that.getuserInfo.id
            const loading = that.$loading({
              lock: true,
              text: '更改中',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            await that.$store.dispatch('UpdateUser', that.userForm).then(async () => {
              loading.close();
              that.$message({message: '更改成功', type: 'success', showClose: true});
              console.log('正在更新用户数据')
              await this.$store.dispatch('ReqUserInfo');
              // await this.$store.dispatch('Logout');
              // Message.error('用户信息已更改，请重新登录！');
              //回到登录页，重新获取一个新的学生证
              // await this.$router.push('/login');
            }).catch((error) => {
              loading.close();
              console.log('出错了')
            })
          }
        });
      },
      async updateTouxiang() {
        await reqUserInfo().then((res) => {
          this.userForm.photoUrl = res.photoUrl,
              this.userForm.id = res.id,
              this.userForm.personalSignature = res.personalSignature,
              this.userForm.userName = res.userName,
              this.userForm.studentName = res.studentName,
              this.userForm.phoneNo = res.phoneNo,
              this.userForm.studentId = res.studentId,
              this.schoolName = res.schoolName,
              this.campusName = res.campusName
        })
      }
    },
   async mounted() {
         await this.updateTouxiang();
   },
}
</script>

<style scoped>
.userInfo{
  width: 1200px;
  height: 920px;
  /*border: 1px solid #FFB3B3;*/
  border-radius: 20px 20px 0 0;
  margin: 0 auto;
  background-color: white;
}
.userInfo h1{
  width: 80px;
  margin: 0 auto;
}
.el-image{
  margin-left: 40%;
  margin-top: 10px;
}
.upload-demo{
  width: 250px;
  margin-left: 540Px
}
.item1{
  margin-top: 30px;
}

</style>
